<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="时间轮,Timer,Schedule," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="原文地址：https://crossoverjie.top

前言节前有更新一篇定时任务的相关文章《延时消息之时间轮》，有朋友提出希望可以完整的介绍下常见的定时任务方案，于是便有了这篇文章。">
<meta property="og:type" content="article">
<meta property="og:title" content="定时任务方案大百科">
<meta property="og:url" content="http://crossoverjie.top/2019/10/14/algorithm/timer-detail/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="原文地址：https://crossoverjie.top

前言节前有更新一篇定时任务的相关文章《延时消息之时间轮》，有朋友提出希望可以完整的介绍下常见的定时任务方案，于是便有了这篇文章。">
<meta property="og:image" content="https://i.loli.net/2019/10/13/6CGWqQp43avTsLx.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/dWENybZVTeaukiI.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/Lzb1HNYPRlGuDtV.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/nW7rRdGmUhZJ9B4.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/pdAFsRBaiLvUXnx.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/dnM9G8tqAo5Iigp.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/MCaxQLnEOdWhkP6.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/yq8um7egtYMUR4P.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/obDHQ84ZitJ5nsv.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/1gq4aX6wJzCKYRy.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/tRFa8uQWrCwdTAs.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/LEAtVPxJalzkY72.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/dgMlfCHoLbrS81R.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/X146xsFrZefuWdP.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/vYkj8HGn9hFsRIK.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/S5giR8ukcfJAhzB.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/5ulvg6csiprkGYy.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/gyJEMni9WjQ528h.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/gWu6BFw9KLrnYDO.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/YyRvDxC4r16zKfH.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/RlwgZ6SybYf7h9C.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/rRUDnSjGloHfyZP.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/h7ZszAwluP6GIpy.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/kPewBVyFgsXzpuR.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/KmYwjU7345VbZvo.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/yq8um7egtYMUR4P.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/WDseB5zkGUHIjSy.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/dcDfJExQposvGFU.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/UjRbE4wa7c2og1N.jpg">
<meta property="og:image" content="https://i.loli.net/2019/10/13/t9B5JWNwgxOpTQy.jpg">
<meta property="og:updated_time" content="2019-10-13T14:59:06.169Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="定时任务方案大百科">
<meta name="twitter:description" content="原文地址：https://crossoverjie.top

前言节前有更新一篇定时任务的相关文章《延时消息之时间轮》，有朋友提出希望可以完整的介绍下常见的定时任务方案，于是便有了这篇文章。">
<meta name="twitter:image" content="https://i.loli.net/2019/10/13/6CGWqQp43avTsLx.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2019/10/14/algorithm/timer-detail/"/>

  <title> 定时任务方案大百科 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                定时任务方案大百科
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2019-10-14T08:13:00+08:00" content="2019-10-14">
              2019-10-14
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/算法/" itemprop="url" rel="index">
                    <span itemprop="name">算法</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/算法/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/算法/Java/Netty/" itemprop="url" rel="index">
                    <span itemprop="name">Netty</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2019/10/14/algorithm/timer-detail/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/10/14/algorithm/timer-detail/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2019/10/14/algorithm/timer-detail/" class="leancloud_visitors" data-flag-title="定时任务方案大百科">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/10/13/6CGWqQp43avTsLx.jpg" alt=""></p>
<blockquote>
<p>原文地址：<a href="https://crossoverjie.top/">https://crossoverjie.top</a></p>
</blockquote>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>节前有更新一篇定时任务的相关文章<a href="https://crossoverjie.top/2019/09/27/algorithm/time%20wheel/">《延时消息之时间轮》</a>，有朋友提出希望可以完整的介绍下常见的定时任务方案，于是便有了这篇文章。</p>
<a id="more"></a>
<h1 id="Timer"><a href="#Timer" class="headerlink" title="Timer"></a>Timer</h1><p>本次会主要讨论大家使用较多的方案，首先第一个就是 <code>Timer</code> 定时器，它可以在指定时间后运行或周期性运行任务；使用方法也非常简单：</p>
<p><img src="https://i.loli.net/2019/10/13/dWENybZVTeaukiI.jpg" alt=""></p>
<p>这样便可创建两个简单的定时任务，分别在 <code>3s/5s</code> 之后运行。</p>
<p>使用起来确实很简单，但也有不少毛病，想要搞清楚它所存在的问题首先就要理解其实现原理。</p>
<h2 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h2><p>定时任务要想做到按照我们给定的时间进行调度，那就得需要一个可以排序的容器来存放这些任务。</p>
<p>在 <code>Timer</code> 中内置了一个 <code>TaskQueue</code> 队列，用于存放所有的定时任务。</p>
<p><img src="https://i.loli.net/2019/10/13/Lzb1HNYPRlGuDtV.jpg" alt=""></p>
<p>其实本质上是用数组来实现的一个<code>最小堆</code>，它可以让每次写入的定时任务都按照执行时间进行排序，保证在堆顶的任务执行时间是最小的。</p>
<p>这样在需要执行任务时，每次只需要取出堆顶的任务运行即可，所以它取出任务的效率很高为<img src="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg" alt="">。</p>
<p>结合代码会比较容易理解：</p>
<p><img src="https://i.loli.net/2019/10/13/nW7rRdGmUhZJ9B4.jpg" alt=""></p>
<p>在写入任务的时候会将一些基本属性存放起来（任务的调度时间、周期、初始化任务状态等），最后就是要将任务写入这个内置队列中。</p>
<p><img src="https://i.loli.net/2019/10/13/pdAFsRBaiLvUXnx.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/dnM9G8tqAo5Iigp.jpg" alt=""></p>
<p>在任务写入过程中最核心的方法便是这个 <code>fixUp()</code> ,它会将写入的任务从队列的中部通过执行时间与前一个任务做比对，一直不断的向前比较。</p>
<p>如果这个时间是最早执行的，那最后将会被移动到堆顶。</p>
<p><img src="https://i.loli.net/2019/10/13/MCaxQLnEOdWhkP6.jpg" alt=""></p>
<p>通过这个过程可以看出 <code>Timer</code> 新增一个任务的时间复杂度为<img src="https://i.loli.net/2019/10/13/yq8um7egtYMUR4P.jpg" alt="">。</p>
<hr>
<p>再来看看它执行任务的过程，其实在初始化 <code>Timer</code> 的时候它就会在后台启动一个线程用于从 <code>TaskQueue</code> 队列中获取任务进行调度。</p>
<p><img src="https://i.loli.net/2019/10/13/obDHQ84ZitJ5nsv.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/1gq4aX6wJzCKYRy.jpg" alt=""></p>
<p>所以我们只需要看他的 <code>run()</code> 即可。</p>
<p><img src="https://i.loli.net/2019/10/13/tRFa8uQWrCwdTAs.jpg" alt=""></p>
<p>从这段代码中很明显可以看出这个线程是一直不断的在调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">task = queue.getMin();</div></pre></td></tr></table></figure>
<p>来获取任务，最后使用 <code>task.run()</code> 来执行任务。</p>
<p><img src="https://i.loli.net/2019/10/13/LEAtVPxJalzkY72.jpg" alt=""></p>
<p>从 <code>getMin()</code> 方法中可以看出和我们之前说的一致，每次都是取出堆顶的任务执行。</p>
<p>一旦取出来的任务执行时间满足要求便可运行，同时需要将它从这个最小堆实现的队列中删除；也就是调用的 <code>queue.removeMin()</code> 方法。</p>
<p><img src="https://i.loli.net/2019/10/13/dgMlfCHoLbrS81R.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/X146xsFrZefuWdP.jpg" alt=""></p>
<p>其实它的核心原理和写入任务类似，只不过是把堆尾的任务提到堆顶，然后再依次比较将任务往后移，直到到达合适的位置。</p>
<blockquote>
<p>从刚才的写入和删除任务的过程中其实也能看出，这个最小堆只是相对有序并不是绝对的有序。</p>
</blockquote>
<p>源码看完了，自然也能得出它所存在的问题了。</p>
<ul>
<li>后台调度任务的线程只有一个，所以导致任务是阻塞运行的，一旦其中一个任务执行周期过长将会影响到其他任务。</li>
<li><code>Timer</code> 本身没有捕获其他异常（只捕获了 <code>InterruptedException</code>），一旦任务出现异常（比如空指针）将导致后续任务不会被执行。</li>
</ul>
<h1 id="ScheduledExecutor"><a href="#ScheduledExecutor" class="headerlink" title="ScheduledExecutor"></a>ScheduledExecutor</h1><p>既然 <code>Timer</code> 存在一些问题，于是在 <code>JDK1.5</code> 中的并发包中推出了 <code>ScheduledThreadPoolExecutor</code> 来替代 <code>Timer</code>，从它所在包路径也能看出它本身是支持任务并发执行的。</p>
<p>先来看看它的类继承图：</p>
<p><img src="https://i.loli.net/2019/10/13/vYkj8HGn9hFsRIK.jpg" alt=""></p>
<p>可以看到他本身也是一个线程池，继承了 <code>ThreadPoolExecutor</code>。</p>
<p><img src="https://i.loli.net/2019/10/13/S5giR8ukcfJAhzB.jpg" alt=""></p>
<p>从他的构造函数中也能看出，本质上也是创建了一个线程池，只是这个线程池中的阻塞队列是一个自定义的延迟队列 <code>DelayedWorkQueue</code>（与 <code>Timer</code> 中的 <code>TaskQueue</code> 作用一致）</p>
<hr>
<h2 id="新建任务"><a href="#新建任务" class="headerlink" title="新建任务"></a>新建任务</h2><p><img src="https://i.loli.net/2019/10/13/5ulvg6csiprkGYy.jpg" alt=""></p>
<p>当我们写入一个定时任务时，首先会将任务写入到 <code>DelayedWorkQueue</code> 中，其实这个队列本质上也是使用数组实现的最小堆。</p>
<p><img src="https://i.loli.net/2019/10/13/gyJEMni9WjQ528h.jpg" alt=""></p>
<p>新建任务时最终会调用到 <code>offer()</code> 方法，在这里也会使用 <code>siftUp()</code> 将写入的任务移动到堆顶。</p>
<p><img src="https://i.loli.net/2019/10/13/gWu6BFw9KLrnYDO.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/10/13/YyRvDxC4r16zKfH.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/10/13/RlwgZ6SybYf7h9C.jpg" alt=""></p>
<p>原理就和之前的 <code>Timer</code> 类似，只不过这里是通过自定义比较器来排序的，很明显它是通过任务的执行时间进行比较的。</p>
<h2 id="运行任务"><a href="#运行任务" class="headerlink" title="运行任务"></a>运行任务</h2><p>所以这样就能将任务按照执行时间的顺序排好放入到线程池中的阻塞队列中。</p>
<p>这时就得需要回顾一下之前线程池的知识点了：</p>
<blockquote>
<p>在线程池中会利用初始化时候的后台线程从阻塞队列中获取任务，只不过在这里这个阻塞队列变为了 <code>DelayedWorkQueue</code>，所以每次取出来的一定是按照执行时间排序在前的任务。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/10/13/rRUDnSjGloHfyZP.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/h7ZszAwluP6GIpy.jpg" alt=""></p>
<p>和 <code>Timer</code> 类似，要在任务取出后调用 <code>finishPoll()</code> 进行删除，也是将最后一个任务提到堆顶，然后挨个对比移动到合适的位置。</p>
<p>而触发消费这个 <code>DelayedWorkQueue</code> 队列的地方则是在写入任务的时候。</p>
<p><img src="https://i.loli.net/2019/10/13/kPewBVyFgsXzpuR.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/KmYwjU7345VbZvo.jpg" alt=""></p>
<p>本质上是调用 <code>ThreadPoolExecutor</code> 的 <code>addWorker()</code> 来写入任务的，所以消费 <code>DelayedWorkQueue</code> 也是在其中触发的。</p>
<p>这里更多的是关于线程池的知识点，不太清楚的可以先看看之前总结的线程池篇，这里就不再赘述。</p>
<ul>
<li><a href="https://crossoverjie.top/2019/05/20/concurrent/threadpool-01/">线程池没你想的那么简单</a></li>
<li><a href="https://crossoverjie.top/2019/06/06/concurrent/threadpool-02/">线程池没你想的那么简单（续）</a></li>
</ul>
<p>原理看完了想必也知道和 <code>Timer</code> 的优势在哪儿了。</p>
<table>
<thead>
<tr>
<th style="text-align:center">Timer</th>
<th style="text-align:center">ScheduledThreadPoolExecutor</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">单线程阻塞</td>
<td style="text-align:center">多线程任务互不影响</td>
</tr>
<tr>
<td style="text-align:center">异常时任务停止</td>
<td style="text-align:center">依赖于线程池，单个任务出现异常不影响其他任务</td>
</tr>
</tbody>
</table>
<p>所以有定时任务的需求时很明显应当淘汰 <code>Timer</code> 了。</p>
<h1 id="时间轮"><a href="#时间轮" class="headerlink" title="时间轮"></a>时间轮</h1><p>最后一个是基于时间轮的定时任务，这个我在上一篇<a href="https://crossoverjie.top/2019/09/27/algorithm/time%20wheel/">《延时消息之时间轮》</a>有过详细介绍。</p>
<p>通过源码分析我们也可以来做一个对比：</p>
<table>
<thead>
<tr>
<th style="text-align:center"></th>
<th style="text-align:center">ScheduledThreadPoolExecutor</th>
<th style="text-align:center">基于时间轮 </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">写入效率</td>
<td style="text-align:center"><img src="https://i.loli.net/2019/10/13/yq8um7egtYMUR4P.jpg" alt="">基于最小堆，任务越多效率越低</td>
<td style="text-align:center"><img src="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg" alt=""> 与 <code>HashMap</code> 的写入类似，效率很高。</td>
</tr>
<tr>
<td style="text-align:center">执行效率</td>
<td style="text-align:center"><img src="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg" alt=""> 每次取出第一个，效率很高</td>
<td style="text-align:center"><img src="https://i.loli.net/2019/10/13/SQiJdxYb6LrIDtN.jpg" alt=""> 每秒拨动一个指针取出任务</td>
</tr>
</tbody>
</table>
<p>所以当写入的任务较多时，推荐使用时间轮，它的写入效率更高。</p>
<p>但任务很少时其实 <code>ScheduledThreadPoolExecutor</code> 也不错，毕竟它不会每秒都去拨动指针消耗 <code>CPU</code> ，而是一旦没有任务线程会阻塞直到有新的任务写入进来。</p>
<h2 id="RingBufferWheel-更新"><a href="#RingBufferWheel-更新" class="headerlink" title="RingBufferWheel 更新"></a>RingBufferWheel 更新</h2><p>在之前的<a href="https://crossoverjie.top/2019/09/27/algorithm/time%20wheel/">《延时消息之时间轮》</a>中自定义了一个基于时间轮的定时任务工具 <code>RingBufferWheel</code> ，在网友的建议下这次顺便也做了一些调整，优化了 API 也新增了取消任务的 API。</p>
<p><img src="https://i.loli.net/2019/10/13/WDseB5zkGUHIjSy.jpg" alt=""></p>
<p>在之前的 API 中，每当新增一个任务都要调用一下 <code>start()</code>，感觉很怪异；这次直接将启动函数合并到 <code>addTask</code> 中，使用起来更加合理。</p>
<p>同时任务的写入也支持并发了。</p>
<p><img src="https://i.loli.net/2019/10/13/dcDfJExQposvGFU.jpg" alt=""><br><img src="https://i.loli.net/2019/10/13/UjRbE4wa7c2og1N.jpg" alt=""></p>
<p>不过这里需要注意的是 <code>start()</code> 在并发执行的时候只能执行一次，于是就利用了 <code>CAS</code> 来保证同时只有一个线程可以执行成功。</p>
<p>同时在新增任务的时候会返回一个 <code>taskId</code> ，利用此 ID 便可实现取消任务的需求（虽然是比较少见），使用方法如下：</p>
<p><img src="https://i.loli.net/2019/10/13/t9B5JWNwgxOpTQy.jpg" alt=""></p>
<p>感兴趣的朋友可以看下源码也很容易理解。</p>
<h1 id="分布式定时任务"><a href="#分布式定时任务" class="headerlink" title="分布式定时任务"></a>分布式定时任务</h1><p>最后再扩展一下，上文我们所提到的所有方案都是单机版的，只能在单个进程中使用。</p>
<p>一旦我们需要在分布式场景下实现定时任务的高可用、可维护之类的需求就得需要一个完善的分布式调度平台的支持。</p>
<p>目前市面上流行的开源解决方案也不少：</p>
<ul>
<li><a href="https://github.com/xuxueli/xxl-job/" target="_blank" rel="external">xxl_job</a></li>
<li><a href="https://github.com/elasticjob/elastic-job-lite" target="_blank" rel="external">elastic_job</a></li>
<li><a href="https://github.com/ltsopensource/light-task-scheduler" target="_blank" rel="external">light-task-scheduler</a></li>
</ul>
<p>我个人在工作中只使用过前面两者，都能很好的解决分布式调度的需求；比如高可用、统一管理、日志报警等。</p>
<p>当然这些开源工具其实在定时调度这个功能上和上文中所提到的一些方案是分不开的，只是需要结合一些分布式相关的知识；比远程调用、统一协调、分布式锁、负载均衡之类的。</p>
<p>感兴趣的朋友可以自行查看下他们的源码或官方文档。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>一个小小的定时器其实涉及到的知识点还不少，包括数据结构、多线程等，希望大家看完多少有些帮助，顺便帮忙点赞转发搞起🥳。</p>
<p>本文所涉及到的所有源码：</p>
<p><a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">https://github.com/crossoverJie/cim</a></p>
<p><strong>你的点赞与分享是对我最大的支持</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/时间轮/" rel="tag">#时间轮</a>
          
            <a href="/tags/Timer/" rel="tag">#Timer</a>
          
            <a href="/tags/Schedule/" rel="tag">#Schedule</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/09/27/algorithm/time wheel/" rel="next" title="延时消息之时间轮">
                <i class="fa fa-chevron-left"></i> 延时消息之时间轮
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Timer"><span class="nav-number">2.</span> <span class="nav-text">Timer</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#实现原理"><span class="nav-number">2.1.</span> <span class="nav-text">实现原理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ScheduledExecutor"><span class="nav-number">3.</span> <span class="nav-text">ScheduledExecutor</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#新建任务"><span class="nav-number">3.1.</span> <span class="nav-text">新建任务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#运行任务"><span class="nav-number">3.2.</span> <span class="nav-text">运行任务</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#时间轮"><span class="nav-number">4.</span> <span class="nav-text">时间轮</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#RingBufferWheel-更新"><span class="nav-number">4.1.</span> <span class="nav-text">RingBufferWheel 更新</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分布式定时任务"><span class="nav-number">5.</span> <span class="nav-text">分布式定时任务</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2019/10/14/algorithm/timer-detail/';
      var disqus_title = "定时任务方案大百科";
      var disqus_url = 'http://crossoverjie.top/2019/10/14/algorithm/timer-detail/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
